package controllers

import (
	"NewYork/models"
	beego "github.com/beego/beego/v2/server/web"
)

type NewController struct {
	beego.Controller
}
type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewController) Add() {
	title := c.GetString("title")
	types := c.GetString("types")
	var news = models.News{
		Title: title,
		Types: types,
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

// func (c *NewController) List() {
//
// }
func (c *NewController) Up() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	types := c.GetString("types")
	var news = models.News{
		Title: title,
		Types: types,
	}
	err := models.DB.Where("id = ?", id).Updates(&news).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.News{}, id).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
